import { HttpService } from '../service/httpService/http.service';
import { Injectable } from "@angular/core";
import {
    HttpErrorResponse,
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    HttpResponse
} from "@angular/common/http";

import { Observable } from "rxjs";
import { tap, timeout, retryWhen, delay, scan } from "rxjs/operators";
import { Router } from "@angular/router";
import { LocalStorageService } from '../service/localStorageService/local-storage.service';
import { NzMessageService } from 'ng-zorro-antd';


/** 超时时间 */
const DEFAULTTIMEOUT = 8
/** 最大重试次数 */
const MAXRETRYCOUNT = 3


@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

    newtoken: any = {
        accessToken: '',
        refreshToken: '',
        role: '',
    }

    constructor(private router: Router, public http: HttpService, public localStorage: LocalStorageService, private message: NzMessageService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(
            // timeout(DEFAULTTIMEOUT),
            tap(
                (event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse) {
                        console.log(event);
                        var code = event.body.code;

                        if (code === 224) {  // 每进入一个页面都会刷新访问令牌，每半小时会重新获取新的访问令牌，所以访问令牌会过期只有手动修改本地存储的token，这里直接跳到登录页
                            this.createMessage('error');
                            this.router.navigate(['/login']);


                        } else if (code === 200) { // 访问令牌和刷新令牌都不过期，正常通过
                            console.log("访问令牌和刷新令牌都不过期，正常通过");

                        } else if (code === 225) { // 权限不足
                            this.router.navigate(['/home/error']);

                        } else if (code === 201) { // 资源请求失败，如：发送数据格式错误

                        } else if (code === 223) { // 解密失败  暂时不会用到的，无需理会

                        } else if (code === 210) { // 密码错误

                        } else if (code === 222) { // 刷新令牌过期，需重新登陆
                            this.createMessage('error');
                            this.router.navigate(['/login']);

                        } else if (code === 220) {  // 拿到新的访问令牌
                            const token = this.localStorage.getItem('token');
                            this.newtoken.refreshToken = token.refreshToken;
                            this.newtoken.accessToken = event.body.result.access_token;
                            this.newtoken.role = token.role;
                            this.localStorage.setItem('token', this.newtoken);
                            console.log("拿到心的访问令牌");
                        }
                    }
                },

            ),
            // retryWhen(err$ => {
            //     //重试 节奏控制器
            //     return err$.pipe(
            //         scan((errCount, err) => {
            //             if (errCount >= MAXRETRYCOUNT) {
            //                 throw err
            //             }
            //             return errCount + 1
            //         }, 0),
            //         delay(1000),
            //         tap(errCount => {
            //             //副作用
            //             if (errCount == 1) {
            //                 //第一次重试时显示友好信息
            //                 // this.nzNotificationService.info('网络超时','正在重新请求中...')
            //                 console.log("网络超时,正在重新请求中...");

            //             }
            //         })
            //     )
            // })

        );
    }
    createMessage(type: string): void {
        this.message.create(type, `token过期，请重新登录！`);
    }
}